import { Badge, Divider, Input, message, Popover } from 'antd';
import '../style/index.css';
import { useEffect, useState } from 'react';
import workbenchService from '@/api/services/workbenchService';
import { useNavigate } from 'react-router-dom';
import { SvgIcon } from '@/components/icon';
import NotData from '@/components/NotData';
import useWindowWidth from '@/hooks/event/use-window-width';
import DocumentOptimization from './DocumentOptimization';

interface SearchType {
  changeSearchValue: (value: React.ChangeEvent<HTMLInputElement>) => void;
  value: string;
  isCollect?: boolean;
}

export default function AppSearch({ changeSearchValue, value, isCollect = true }: SearchType) {
  const router = useNavigate();
  const { isPc } = useWindowWidth();
  const [count, setCount] = useState(0); //未读消息数量
  const [messagePopoverVisible, setMessagePopoverVisible] = useState(false); //消息通知弹窗
  const [messageList, setMessageList] = useState([
    {
      message: '',
      module: '',
      status: '',
      notification_id: '',
      next_actions: { forward_to: '', display_text: '' },
      detail: '',
    },
  ]);
  const [documentOptimizationVisible, setDocumentOptimizationVisible] = useState(false);

  // 获取消息通知
  const getMessageInform = async () => {
    try {
      const res = await workbenchService.messageInformApi();
      setCount(res.new_count);
      setMessageList(res.notifications);
    } catch (error) {
      message.error(error);
    }
  };
  /**
   * @description: 更改消息通知
   * @return {*}
   */
  const changeMessageInform = async (...obj: any) => {
    let searchData = {
      notification_id: '',
      status: 'IGNORED',
    };
    if (obj[0] === 'all') {
      let list: any = [];
      messageList.forEach((item) => {
        list.push(item.notification_id);
      });
      searchData.notification_id = list;
    } else if (obj[0] === 'PROCESSED') {
      searchData.notification_id = obj[1].notification_id;
      searchData.status = 'PROCESSED';
      router(obj[1].next_actions.forward_to);
    } else {
      searchData.notification_id = obj[1].notification_id;
    }
    try {
      await workbenchService.updateMessageInformApi(searchData);
      setMessagePopoverVisible(false);
      getMessageInform();
    } catch (error) {
      message.error(error);
    }
  };

  useEffect(() => {
    if (!isCollect) {
      return;
    }
    getMessageInform(); //获取消息通知
    //定时获取
    const id = setInterval(() => {
      getMessageInform();
    }, 10000);
    return () => {
      clearInterval(id);
    };
  }, []);

  const messagePopoverContent = (
    <div className="p-1" style={{ width: '332px' }}>
      <div className="flex cursor-pointer items-center justify-between">
        <div className="text-base font-bold text-[#1D2129]">当前通知</div>
        <div
          onClick={() => changeMessageInform('all')}
          // style={count === 0 ? { color: '#C9C9C9' } : {}}
          className={`text-xs  ${count === 0 ? 'text-[#C9C9C9]' : 'text-[#86909C]'}`}
        >
          全部忽略
        </div>
      </div>
      {count > 0 ? (
        <>
          <div className="mt-3 max-h-[400px] overflow-auto">
            {messageList?.map((item, index) => {
              return (
                <div key={index}>
                  <div className="ml-2 flex items-center">
                    {item.status === 'FAILURE' ? (
                      <SvgIcon icon="tz-FAILURE" size="24" className="mr-2 rounded-md" />
                    ) : item.status === 'SUCCESS' ? (
                      <SvgIcon icon="tz-SUCCESS" size="24" className="mr-2 rounded-md" />
                    ) : item.status === 'REJECT' ? (
                      <SvgIcon icon="tz-REJECT" size="24" className="mr-2 rounded-md" />
                    ) : item.status === 'ROLE_CHANGE' ? (
                      <SvgIcon icon="tz-ROLE_CHANGE" size="24" className="mr-2 rounded-md" />
                    ) : (
                      <SvgIcon icon="tz-UNPROCESSED" size="24" className="mr-2 rounded-md" />
                    )}
                    <div className="text-sm">{item.message}</div>
                  </div>
                  <div className="text my-2 ml-10 text-xs">{item.detail}</div>
                  <div className="ml-9 mt-2 flex items-center">
                    {item.next_actions.display_text != '' &&
                      item.next_actions.display_text != '立即处理' && (
                        <div
                          className="message"
                          onClick={() => changeMessageInform('PROCESSED', item)}
                        >
                          {item.next_actions.display_text}
                        </div>
                      )}
                    {item.next_actions.display_text === '立即处理' && (
                      <div
                        className="message"
                        onClick={() => {
                          setDocumentOptimizationVisible(true);
                          setMessagePopoverVisible(false);
                        }}
                      >
                        立即处理
                      </div>
                    )}
                    <div className="message" onClick={() => changeMessageInform('IGNORED', item)}>
                      忽略
                    </div>
                  </div>
                  <Divider style={{ margin: '14px 0px' }} />
                </div>
              );
            })}
          </div>
          <div
            className="mt-2 cursor-pointer text-center text-sm text-[#0080FF]"
            onClick={() => router('/worklayouts/messageCenter')}
          >
            查看所有通知
          </div>
        </>
      ) : (
        <div className="mt-3 h-[230px] overflow-auto pt-10">
          <NotData />
        </div>
      )}
    </div>
  );

  return (
    <div className="flex">
      {isCollect && (
        <div className="pr-3">
          <Popover
            content={messagePopoverContent}
            trigger="click"
            placement="bottomRight"
            // open={count > 0 && messagePopoverVisible}
            open={messagePopoverVisible}
            onOpenChange={setMessagePopoverVisible}
          >
            <Badge count={count} style={{ top: 0, right: 12 }} color="#FC5151" dot>
              {/* <BellOutlined className="text cursor-pointer pr-3 text-2xl" /> */}
              <SvgIcon icon="work-ic5" size={16} className="relative right-3 cursor-pointer" />
            </Badge>
          </Popover>
        </div>
      )}

      <Input
        value={value}
        onChange={changeSearchValue}
        className="!rounded-md "
        style={
          !isPc
            ? {
                height: '32px',
                width: isPc ? '200px' : '100%',
              }
            : {}
        }
        placeholder="搜索"
        suffix={<SvgIcon icon="work-ic6" size={16} />}
      />

      <DocumentOptimization
        visible={documentOptimizationVisible}
        onClose={() => setDocumentOptimizationVisible(false)}
        onOk={() => setDocumentOptimizationVisible(false)}
      />
    </div>
  );
}
